/**
 * @param {ListNode} head
 * @return {ListNode}
 */


//运用双指针遍历链表，然后用一个常量保存前面指针的位置
var reverseList = function(head) {
    let p1=head,p2=null;
    while(p1){
        const store=p1.next;
        p1.next=p2;
        p2=p1;
        p1=store;
    }
    return p2;
};




// 双指针：
var reverseList = function(head) {
    if(!head || !head.next) return head;
    let temp = null, pre = null, cur = head;//定义一个cur指针，指向头结点，定义一个pre指针，初始化为null。
    while(cur) {
        temp = cur.next;//用tmp指针保存cur->next 节点
        cur.next = pre;//翻转操作,改变 cur->next 的指向了，将cur->next 指向pre
        pre = cur;//循环走代码逻辑，继续移动pre和cur指针
        cur = temp;
    }
    // temp = cur = null;
    return pre;
};

// 递归：
var reverse = function(pre, head) {
    if(!head) return pre;//边缘条件判断
    const temp = head.next;
    head.next = pre;
    pre = head
    return reverse(pre, temp);
}

var reverseList = function(head) {
    return reverse(null, head);
};

// 递归2
var reverse = function(head) {
    if(!head || !head.next) return head;
    // 从后往前翻
    const pre = reverse(head.next);
    head.next = pre.next;
    pre.next = head;
    return head;
}

var reverseList = function(head) {
    let cur = head;
    while(cur && cur.next) {
        cur = cur.next;
    }
    reverse(head);
    return cur;
};



